package com.example.myapplication.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.myapplication.entity.User;

import static android.content.Context.MODE_PRIVATE;
import static androidx.constraintlayout.widget.Constraints.TAG;

public class SharedPreferencesDao {

    /**
     * 保存用户信息
     */
    public static void saveUserInfo(Context context, User user){
        SharedPreferences userInfo = context.getSharedPreferences(user.getUserName(), MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//获取Editor
        //得到Editor后，写入需要保存的数据
        editor.putString("userName", user.getUserName());
        editor.putString("password", user.getPassword());
        editor.putString("email", user.getEmail());
        editor.commit();//提交修改
        Log.i(TAG, "保存用户信息成功");
    }
    /**
     * 读取用户信息
     */
    public static User getUserInfo(Context context, String userName){
        SharedPreferences userInfo = context.getSharedPreferences(userName, MODE_PRIVATE);
        String password = userInfo.getString("password", null);
        String email = userInfo.getString("email", null);
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setEmail(email);
        Log.i(TAG, "读取用户信息");
        Log.i(TAG, user.toString());
        return user;
    }

    /**
     * 清空数据
     */
    public static void clearUserInfo(Context context, String name){
        SharedPreferences userInfo = context.getSharedPreferences(name, MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//获取Editor
        editor.clear();
        editor.commit();
        Log.i(TAG, "清空数据");
    }

}
